<?php

// ==============================================================================
//
// This file is part of the WelSpeak.
//
// Create by Edison Liu <support@welfony.com>
// Copyright (c) 2012-2013 welfony.com
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// ==============================================================================

namespace Welfony\Welspeak\WebSocket;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Welfony\Welspeak\Core\Enum\MessageType;

class ChatServer implements MessageComponentInterface
{

    protected $clients;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg)
    {
        $message = json_decode($msg);
        if($message === null) {
            return;
        }

        if ($message->type == MessageType::DeviceTokenUpdate) {
            foreach ($this->clients as $client) {
                if ($from === $client) {
                    $client->userId = $message->userId;
                }
            }
        }

        if ($message->type == MessageType::SendVoiceMessage) {
            $arrMsg = explode('|', $message->data);
            foreach ($this->clients as $client) {
                if ($arrMsg[2] == $client->userId) {
                    $rst = array(
                        'view' => 'chat',
                        'receiverId' => $arrMsg[1]
                    );
                    $client->send(json_encode($rst));
                }
            }
        }

    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "User {$conn->userId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }

}